package cn.lyvust.eais.manage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.lyvust.eais.common.exception.RequestException;
import cn.lyvust.eais.common.util.BeansUtil;
import cn.lyvust.eais.manage.dto.param.evaluation.ProjectItemRecordParam;
import cn.lyvust.eais.manage.dto.result.ProjectItemRecordStatResp;
import cn.lyvust.eais.manage.entity.EvaluationItemAttr;
import cn.lyvust.eais.manage.entity.EvaluationProjectItemRecord;
import cn.lyvust.eais.manage.entity.EvaluationRecordAttachement;
import cn.lyvust.eais.manage.mapper.EvaluationProjectItemRecordMapper;
import cn.lyvust.eais.manage.service.EvaluationItemAttrService;
import cn.lyvust.eais.manage.service.EvaluationProjectItemRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lyvust.eais.manage.service.EvaluationRecordAttachementService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ggzheng
 * @since 2021-01-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EvaluationProjectItemRecordServiceImpl extends ServiceImpl<EvaluationProjectItemRecordMapper, EvaluationProjectItemRecord> implements EvaluationProjectItemRecordService {
    @Autowired
    private EvaluationItemAttrService itemAttrService;
    @Autowired
    private EvaluationRecordAttachementService attachementService;

    @Override
    public IPage<EvaluationProjectItemRecord> listPage(ProjectItemRecordParam param) {
        QueryWrapper wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(param.getId())) {
            wrapper.eq("id", param.getId());
        }
        if (!StringUtils.isEmpty(param.getRecord())) {
            wrapper.eq("record", param.getRecord());
        }
        if (!StringUtils.isEmpty(param.getUserId())) {
            wrapper.eq("user_id", param.getUserId());
        }
        if (!StringUtils.isEmpty(param.getItemId())) {
            wrapper.eq("item_id", param.getItemId());
        }
        if (!StringUtils.isEmpty(param.getCreateBy())) {
            wrapper.eq("create_by", param.getCreateBy());
        }
        if (!StringUtils.isEmpty(param.getAuditStatus())) {
            wrapper.eq("audit_status", param.getAuditStatus());
        }
        wrapper.orderByDesc("update_time");
        Page res = this.page(new Page<>(param.getPage(), param.getPageSize()), wrapper);
        if (res == null || res.getRecords().size() == 0) {
            return null;
        }
        Map<String, String> newContent = new HashMap<>();
        Map<String, EvaluationItemAttr> attrMap = new HashMap<>();
        List<EvaluationProjectItemRecord> records = res.getRecords();
        for (EvaluationProjectItemRecord item : records) {
            try {
                String content = item.getContent();
                Map<String,String> contemtMap = JSONArray.parseObject(content, Map.class);
                for (Map.Entry entry : contemtMap.entrySet()) {
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    EvaluationItemAttr attr = itemAttrService.getById(key);
                    newContent.put(attr.getLabelName(), value);
                    attrMap.put(attr.getLabelName(), attr);
                }
                item.setContent(JSON.toJSONString(newContent));
                item.setContentMap(attrMap);
            } catch (Exception exception) {
                continue;
            }

        }
        return res;
    }

    @Override
    public ProjectItemRecordStatResp stat(ProjectItemRecordParam param) {
        QueryWrapper wrapper = new QueryWrapper();
        String userId = param.getUserId();
        String itemId = param.getItemId();
        if (StringUtils.isEmpty(userId)) {
            throw RequestException.fail("统计失败, 用户ID不能为空!");
        }
        if (StringUtils.isEmpty(itemId)) {
            throw RequestException.fail("统计失败,指标项记录Id不能为空!");
        }
        wrapper.eq("user_id", userId);
        wrapper.eq("item_id", itemId);
        List<EvaluationProjectItemRecord> resList = this.list(wrapper);
        if (CollectionUtils.isEmpty(resList)) {
            return null;
        }
        ProjectItemRecordStatResp result = new ProjectItemRecordStatResp();
        result.setUserId(userId);
        result.setItemId(itemId);
        result.setTotal(resList.size());
        Integer audited = 0;
        Integer unaudited = 0;
        for (EvaluationProjectItemRecord record : resList) {
            if (record.getAuditStatus() == null || record.getAuditStatus() != 1) {
                unaudited += 1;
            } else if (record.getAuditStatus() == 1){
                audited += 1;
            }
        }
        result.setAudited(audited);
        result.setUnaudited(unaudited);
        return result;
    }

    @Override
    public EvaluationProjectItemRecord add(ProjectItemRecordParam param) {
//        if (StringUtils.isEmpty(param.getTitle())) {
//            throw RequestException.fail("添加失败,考核指标项记录名称不能为空!");
//        }
        if (StringUtils.isEmpty(param.getCreateBy())) {
            throw RequestException.fail("添加失败,考核指标项记录添加操作人姓名不能为空!");
        }
        EvaluationProjectItemRecord entity = new EvaluationProjectItemRecord();
        BeanUtils.copyProperties(param, entity);
        this.saveOrUpdate(entity);

        String attachment = param.getAttachment();
        if (StringUtils.isEmpty(attachment)) {
            return entity;
        }
        EvaluationRecordAttachement attachementEntity = new EvaluationRecordAttachement();
        JSONArray attachmentArray = JSON.parseArray(attachment);
        for(int i=0; i < attachmentArray.size(); i++){
            Map<String,String> attachmentMap = attachmentArray.getObject(i, Map.class);
            attachementEntity.setRecordId(entity.getId());
            attachementEntity.setCreateDate(new Date());
            attachementEntity.setExtName(attachmentMap.get("extName"));
            attachementEntity.setFileName(attachmentMap.get("uploadFile"));
            String fileSize = attachmentMap.get("fileSize");
            if (!StringUtils.isEmpty(fileSize)) {
                attachementEntity.setFileSize(Double.parseDouble(fileSize));
            }
            attachementEntity.setFileType(attachmentMap.get("fileType"));
            attachementEntity.setTitle(attachmentMap.get("fileName"));
            attachementEntity.setPicFile(attachmentMap.get("thumbFile"));
            attachementService.save(attachementEntity);
        }
        return entity;
    }

    @Override
    public EvaluationProjectItemRecord update(ProjectItemRecordParam param) {
        if (StringUtils.isEmpty(param.getId())) {
            throw RequestException.fail("修改失败,考核指标项记录主键ID不能为空!");
        }
        if (StringUtils.isEmpty(param.getUpdateBy())) {
            throw RequestException.fail("修改失败,修改操作人姓名不能为空!");
        }
        EvaluationProjectItemRecord entity = this.getById(param.getId());
        BeansUtil.copyPropertiesIgnoreNull(param, entity);

        String attachment = param.getAttachment();
        if (!StringUtils.isEmpty(attachment)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("record_id", entity.getId());
            EvaluationRecordAttachement attachementEntity = attachementService.getOne(wrapper);
            JSONArray attachmentArray = JSON.parseArray(attachment);
            for(int i=0; i < attachmentArray.size(); i++){
                Map<String,String> attachmentMap = attachmentArray.getObject(i, Map.class);
                attachementEntity.setCreateDate(new Date());
                attachementEntity.setExtName(attachmentMap.get("extName"));
                attachementEntity.setFileName(attachmentMap.get("uploadFile"));
                String fileSize = attachmentMap.get("fileSize");
                if (!StringUtils.isEmpty(fileSize)) {
                    attachementEntity.setFileSize(Double.parseDouble(fileSize));
                }
                attachementEntity.setFileType(attachmentMap.get("fileType"));
                attachementEntity.setTitle(attachmentMap.get("fileName"));
                attachementEntity.setPicFile(attachmentMap.get("thumbFile"));
                attachementService.updateById(attachementEntity);
            }
        }

        this.updateById(entity);
        return entity;
    }
}
